package com.example.bailin.giftsay.main;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bailin.giftsay.R;
import com.example.bailin.giftsay.baseclass.BaseActivity;
import com.example.bailin.giftsay.entity.SearchGiftEntity;
import com.example.bailin.giftsay.guide.PopupClick;
import com.example.bailin.giftsay.main.adapter.PxAdapter;
import com.example.bailin.giftsay.main.adapter.SearchAdapter;
import com.example.bailin.giftsay.sort.activity.SearchFragment.DPFragment;
import com.example.bailin.giftsay.sort.activity.SearchFragment.GLFragment;
import com.example.bailin.giftsay.sort.adapter.SearchOfVPAdapter;
import com.example.bailin.giftsay.tool.MyApp;
import com.example.bailin.giftsay.tool.NetTool;
import com.example.bailin.giftsay.tool.UrlProvide;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * Created by bailin on 16/8/23.
 * <p/>
 * 搜索的Activity
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, SearchListener {

    private RecyclerView rv;
    private ImageView ivReturn; // 反回
    private EditText etSearch;
    private TextView tvSearch; // 搜索
    private RelativeLayout rlSkip;
    private TabLayout tlSearch;
    private ViewPager vpSearch;
    private RelativeLayout rlSearchAfter; // 隐藏的布局搜索之后显示出来的布局
    private RelativeLayout rlSearchBefore; // 搜索之前的布局点击搜索后隐藏
    private ImageView ivSearchArrange; // 搜索前隐藏点击搜索后搜索隐藏本排序图片显示
    private String str;
    private PopupWindow popupWindow;
    private PxAdapter pxAdapter;
    private int type;
    private int index;
    private UpDataEvent upDataEvent;

    @Override
    protected int setLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        rv = bindView(R.id.rv_search);
        ivReturn = bindView(R.id.iv_search_return);
        etSearch = bindView(R.id.et_search_id);
        tvSearch = bindView(R.id.tv_search);
        rlSkip = bindView(R.id.rl_skip_xlsq);
        tlSearch = bindView(R.id.tablayout_search);
        vpSearch = bindView(R.id.viewpage_search);
        rlSearchAfter = bindView(R.id.rl_search_after);
        rlSearchBefore = bindView(R.id.rl_search_before);
        ivSearchArrange = bindView(R.id.iv_search_arrange);
        ivSearchArrange.setOnClickListener(this);
        rlSkip.setOnClickListener(this);
        ivReturn.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        upDataEvent = new UpDataEvent();
        tool().getData(UrlProvide.SEARCH, SearchGiftEntity.class, new NetTool.NetInterface<SearchGiftEntity>() {
            @Override
            public void onSuccess(SearchGiftEntity searchGiftEntity) {
                SearchAdapter adapter = new SearchAdapter();
                GridLayoutManager manager = new GridLayoutManager(MyApp.getContext(), 5);
                adapter.setEntity(searchGiftEntity);
                adapter.setSearchListener(SearchActivity.this);
                rv.setLayoutManager(manager);
                rv.setAdapter(adapter);
            }

            @Override
            public void onError(String errorMsg) {
            }
        });

        SearchOfVPAdapter vpAdapter = new SearchOfVPAdapter(getSupportFragmentManager());
        ArrayList<Fragment> fragments = new ArrayList<>();
        ArrayList<String> strings = new ArrayList<>();
        fragments.add(new DPFragment());
        fragments.add(new GLFragment());
        strings.add("单品");
        strings.add("攻略");
        vpAdapter.setFragments(fragments);
        vpAdapter.setStrings(strings);
        vpSearch.setAdapter(vpAdapter);
        tlSearch.setupWithViewPager(vpSearch);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0) {
                    rlSearchBefore.setVisibility(View.VISIBLE);
                    rlSearchAfter.setVisibility(View.GONE);
                }
                if (s != str) {
                    tvSearch.setVisibility(View.VISIBLE);
                    ivSearchArrange.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        vpSearch.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                type = position;
                index = 0;
                upDataEvent.setType(position);
                upDataEvent.setPosition(0);
                EventBus.getDefault().post(upDataEvent);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search_return:
                finish();
                break;
            case R.id.rl_skip_xlsq:
                Intent intent = new Intent(MyApp.getContext(), SelectActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_search:
                String content = etSearch.getText().toString();
                str = handle(content);
                if (str.equals("")) {
                    Toast.makeText(this, "请输入关键字进行搜索", Toast.LENGTH_SHORT).show();
                } else {
                    eventBus(str);
                    rlSearchBefore.setVisibility(View.GONE);
                    rlSearchAfter.setVisibility(View.VISIBLE);
                    tvSearch.setVisibility(View.GONE);
                    ivSearchArrange.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_search_arrange:
                initPopupWindowPaixu(v);
                break;
        }
    }

    private void initPopupWindowPaixu(View v) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        } else {
            View customView1 = getLayoutInflater().inflate(R.layout.item_paixu_listview, null);
            ListView lv = (ListView) customView1.findViewById(R.id.lv_paixu);
            pxAdapter = new PxAdapter();
            pxAdapter.setPopupClick(new PopupClick() {
                @Override
                public void itemOnClick(int position) {
                    popupWindow.dismiss();
                    index = position;

                    upDataEvent.setPosition(position);
                    EventBus.getDefault().post(upDataEvent);
                }
            });
            pxAdapter.setIndex(index);
            pxAdapter.setType(type);
            lv.setAdapter(pxAdapter);
            popupWindow = new PopupWindow(customView1, 450, ViewGroup.LayoutParams.WRAP_CONTENT);
            customView1.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                        popupWindow = null;
                    }
                    return false;
                }
            });
            popupWindow.setFocusable(true);
        }
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, 970, 230);
        popupWindow.showAsDropDown(v, 0, 5);
    }

    private String handle(String content) {
        return content.replace(" ", "");
    }

    @Override
    public void onClick(String name) {
        etSearch.setText(name);
        eventBus(etSearch.getText().toString());
        rlSearchBefore.setVisibility(View.GONE);
        rlSearchAfter.setVisibility(View.VISIBLE);
        tvSearch.setVisibility(View.GONE);
        ivSearchArrange.setVisibility(View.VISIBLE);
    }

    // EventBus发送网址
    private void eventBus(String url) {
        index = 0;
        EventBus.getDefault().post(url);
    }
}
